import fileio from '@ohos.fileio';
import request from '@ohos.request';
import { httpClient, RequestParam } from './HttpClient';


export class DemandResourceManager {
    private readonly targetUrl: string = "";
    private readonly storeDir: string = globalThis.desktopContext.filesDir;
    private readonly fileSeparator: string = "/";
    private imageUrlCache: string[] = [];
    private readonly fileUrlPrefix: string = "file://"
    private static DEMAND_RESOURCE_MANAGER: DemandResourceManager;

    constructor() {
    }

    public static getInstance() {
        if (DemandResourceManager.DEMAND_RESOURCE_MANAGER == undefined) {
            DemandResourceManager.DEMAND_RESOURCE_MANAGER = new DemandResourceManager();
        }
        return DemandResourceManager.DEMAND_RESOURCE_MANAGER;
    }

    async getDemandResource() {
        let videoList: VideoInfo[] = await this.obtainResourceFromNet(); //从网络获取资源
        if (videoList == undefined || videoList.length == 0) {
            AppStorage.setOrCreate("canPlay", false);
            videoList = this.obtainResourceFromLocal(); //从本地获取资源
        }
        return videoList;
    }

    private async obtainResourceFromNet() {
        let requestParam: RequestParam = {
            method: "GET",
            header: {
                'content-type': 'application/json'
            },
            readTimeout: 60000,
            connectTimeout: 60000
        }

        let videoList: VideoInfo[] = await httpClient.requestHttp(this.targetUrl, requestParam);
        console.info("Demand:the result from server:" + JSON.stringify(videoList));
        if (videoList != undefined && videoList.length > 0) {
            AppStorage.setOrCreate("canPlay", true); //在联网和有资源的情况下显示播放按钮
            let result = this.reduceDupImage(videoList);
            result.forEach((videoInfo) => {

                //                let temp = videoInfo.img.split('/');
                //                let filePath=`${this.storeDir}/${temp[temp.length - 1]}`;
                let filePath = this.getFilePath(videoInfo.img);
                this.download(videoInfo.img, filePath);
            })
        }
        return videoList;
    }

    getFilePath(url: string) {
        let lastIndex: number = url.lastIndexOf(this.fileSeparator);
        let filePath: string = `${this.storeDir}/${url.substring(lastIndex + 1)}`;
        return filePath;
    }

    reduceDupImage(videoList: VideoInfo[]) {
        let result = videoList.filter((item) => {
            let fileURL = this.fileUrlPrefix + this.getFilePath(item.img);
            return!this.imageUrlCache.includes(fileURL);
        })
        console.info("Demand:the reduced videolist:" + JSON.stringify(result));
        return result;
    }

    obtainResourceFromLocal() {
        let localVideoList: VideoInfo[] = [];
        if (this.imageUrlCache.length > 0) {
            localVideoList = this.buildVideoList(this.imageUrlCache);
        } else {
            localVideoList = this.buildVideoList(this.obtainImgFromSystem());
        }
        console.info("Demand:local video list==>"+JSON.stringify(localVideoList));
        return localVideoList;
    }

    private buildVideoList(fileArr: string[]) {
        let videoList: VideoInfo[] = [];
        fileArr.forEach((imageUrl) => {
            videoList.push({
                url: "",
                img: imageUrl,
                name: ""
            })
        })
        return videoList;
    }


    /**
     *从系统中获取海报资源，先使用fileio实现，后续采用fs
     */
    private obtainImgFromSystem() {
        let dir = fileio.opendirSync(this.storeDir);
        fileio.closeSync
        let imageFileUrls: string[] = [];
        try {
            let fileName: string;
            while ((fileName = dir.readSync().name) != null) {
                let fileSuffix: string = fileName.substring(fileName.lastIndexOf(".") + 1);
                if (fileSuffix == "png" || fileSuffix == "jpg" || fileSuffix == "jpeg") {
                    console.info("Demand:the file suffix:" + fileSuffix);
                    imageFileUrls.push(this.fileUrlPrefix + this.storeDir + "/" + fileName);
                }
            }

            //fs 实现
            //            let options = {
            //                "recursion": false,
            //                "listNum": 0,
            //                "filter": {
            //                    "suffix": [".png", ".jpg", ".jpeg"],
            //                    "fileSizeOver": 1024,
            //                }
            //            };
            //            let filenames: string[] = fs.listFileSync(this.storeDir, options);
            //            let imageUrls = filenames.map((file) => {
            //                return this.fileUrlPrefix+this.storeDir+"/"+file;
            //            })
            //            console.info("Demand:listFile succeed");
            //            return imageUrls;
        } catch (err) {
            console.info("Demand:get file fail:" + err);
        } finally {
            dir.closeSync();
        }
        console.info("Demand:the result from system:" + JSON.stringify(imageFileUrls))
        return imageFileUrls;
    }

    private async download(url: string, filePath: string) {
        try {
            console.info(`Demand:url to load :${url},file path to store :${filePath} `);
            let downloadTask = await request.downloadFile(
            globalThis.desktopContext,
                {
                    url: url,
                    filePath: filePath
                });
            downloadTask.on('complete', () => {
                this.imageUrlCache.push(this.fileUrlPrefix + filePath);
            });
        } catch (err) {
            console.info("Demand:download fail:" + JSON.stringify(err));
        }
    }
}


class VideoInfo {
    url: string;
    img: string;
    name: string;
}